package com.sky.controller.user;


import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController("userOrderController")
@Slf4j
@RequestMapping("/user/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @PostMapping("/submit")
    public Result<OrderSubmitVO> submitOrder(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        log.info("下单数据为:{}", ordersSubmitDTO);
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        OrderSubmitVO orderSubmitVO = orderService.submitOrder(orders);
        return Result.success(orderSubmitVO);
    }

    /**
     * 根据订单id查询详细订单
     *
     * @param id
     * @return
     */
    @GetMapping("/orderDetail/{id}")
    public Result<OrderVO> orderDetail(@PathVariable Long id) {
        log.info("订单Id为:{}", id);
        OrderVO vo = orderService.detailOrder(id);
        return Result.success(vo);
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @GetMapping("/historyOrders")
    public Result<PageResult> historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        log.info("查询参数为:{}", ordersPageQueryDTO);
        PageResult pageResult = orderService.pageQuery(ordersPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @PostMapping("/repetition/{id}")
    public Result repetition(@PathVariable Long id) {
        log.info("再来一次订单id为:{}", id);
        orderService.repetitionOrder(id);
        return Result.success();
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @PutMapping("/cancel/{id}")
    public Result cancel(@PathVariable Long id) {
        log.info("取消订单id为:{}", id);
        orderService.cancelOrder(id);
        return Result.success();
    }

    /**
     * 催单
     * @param id
     * @return
     */
    @GetMapping("/reminder/{id}")
    public Result reminder(@PathVariable Long id) {
        log.info("催单订单id为:{}", id);
        Orders order = orderMapper.getOrderById(id);
        if (order == null && !order.getPayStatus().equals(Orders.PAID)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //ws 提示接单
        Map map = new HashMap();
        map.put("type", 2);//消息类型，1表示来单提醒 表示催单
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());
        String JSON = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(JSON);
        return Result.success();
    }

    /**
     * 支付
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) {
        log.info("支付信息:{}", ordersPaymentDTO);
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersPaymentDTO, orders);
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        orderPaymentVO.setNonceStr("111");
        orderPaymentVO.setPackageStr("111");
        orderPaymentVO.setPaySign("111");
        orderPaymentVO.setTimeStamp("111");
        orderPaymentVO.setSignType("111");

        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orderMapper.updateOrder(orders);

        OrderSubmitVO vo = orderMapper.selectOrderById(orders);
        if (vo == null && !orders.getPayStatus().equals(Orders.PAID)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //ws 提示接单
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", vo.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        String JSON = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(JSON);
        return Result.success(orderPaymentVO);
    }
}